package com.gugee.tiktok.common.model.dal.blogger;

import com.gugee.tiktok.common.model.mysql.Blogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.List;
import java.util.stream.Collectors;

public class BloggerExtRepositoryImpl implements BloggerExtRepository {
    @Autowired
    @Lazy
    BloggerRepository bloggerRepository;

    public void insertOrUpdate(Blogger blogger, String operator) {
        insertOrUpdateByCondition(blogger, false, operator);
    }

    public void insertWhenNotExists(Blogger blogger, String operator) {
        insertOrUpdateByCondition(blogger, true, operator);
    }

    public List<Long> getNotExistBloggerIds(List<Long> uids) {
        return uids.stream().filter(uid -> !bloggerRepository.existsByoUid(uid)).collect(Collectors.toList());
    }

    private void insertOrUpdateByCondition(Blogger blogger, boolean isSkipUpdate, String operator) {
        // lock here
        var optionalBlogger = bloggerRepository.findByoUid(blogger.getOUid());

        if (!optionalBlogger.isPresent()) {
            blogger.setCreateBy(operator);
            blogger.setUpdateBy(operator);
            bloggerRepository.save(blogger);
        } else if (optionalBlogger.isPresent() && !isSkipUpdate) {
            var origin = optionalBlogger.get();
            blogger.setId(origin.getId());
            blogger.setCreateTime(origin.getCreateTime());
            blogger.setCreateBy(origin.getCreateBy());
            blogger.setUpdateBy(operator);
            bloggerRepository.save(blogger);
        }
    }
}
